<?php
namespace Manage\Controller;

use Common\Model\OrderModel;
use Common\Model\RefundModel;
use Think\Controller;
use Think\Model;


class RefundController extends BaseController
{
    /**
     * 采购商品列表
     */
    public function index()
    {
        $p = max(I('param.p'), 1);
        $num = max(I('param.num'), 20);
        $view = I('param.view', 1);
        $this->assign('p', $p);
        $this->assign('num', $num);
        $this->assign('view', $view);
        $order_field = I('param.order_field', 'id');
        $order = I('param.order', 'desc');
        $this->assign('order_field', $order_field);
        $this->assign('order', $order);
        $sunxu = $order == 'asc' ? 'desc' : 'asc';
        $this->assign('order', $sunxu);

        $order = array($order_field => $order);

        $search_field = I('param.search_field', 'name');
        $search = I('param.search');
        if ($view == 1) {
            $where[] = " (a.status='2' and a.type='1') OR (a.status='2' and a.type='2') OR (a.status='4' and a.type='3')";
        } elseif ($view == 2) {
            $where[] = " a.status='5' ";
        } elseif ($view == 9) {
            $where[] = " (a.status='2' and a.type='1') OR (a.status='2' and a.type='2') OR (a.status='4' and a.type='3') OR a.status='5' ";
        }
        if ($search && $search_field) {
            $this->assign('search_field', $search_field);
            $this->assign('search', $search);
            if ($search_field == 'order_id') {
                $search_field = 'a.' . $search_field;
            } else {
                $search_field = 'b.' . $search_field;
            }
            $where[] = " {$search_field} LIKE '%{$search}%' ";
        }
        $count = M('b2c_refund_money')
            ->alias('a')
            ->join(C('DB_PREFIX') . 'b2c_orders b on a.order_id=b.order_id')
            ->where($where)
            ->count();
        if ($count > 0) {
            $Page = new \Think\Page($count, $num);
            $show = $Page->show();

            $list = M('b2c_refund_money')
                ->alias('a')
                ->join(C('DB_PREFIX') . 'b2c_orders b on a.order_id=b.order_id')
                ->field('a.*,b.createtime,b.ship_name,b.ship_mobile,b.local_name')
                ->where($where)
                ->order($order)
                ->page($p, $num)
                ->select();
            //dump($list);
            foreach ($list as &$item) {
                if ($item['store_work_logs']) {
                    $tmp = json_decode($item['store_work_logs'], true);
                    $price = array_pop($tmp);
                    $item['store_money'] = $price['store_money'];
                }
                $item['state'] = $this->_getStatus($item['status']);

            }
            $this->assign('list', $list);
            $this->assign('page', $show);
        }
        $this->display();
    }

    protected function _getStatus($status)
    {
        switch ($status) {
            case '0':
                $status_desc = '已取消';
                break;
            case '1':
                $status_desc = '待初审核中';
                break;
            case '2':
                $status_desc = '初审成功';
                break;
            case '3':
                $status_desc = '用户已发退货';
                break;
            case '4':
                $status_desc = '确认收到退货';
                break;
            case '5':
                $status_desc = '退货退款完成';
                break;
            case '6':
                $status_desc = '重新申请';
                break;
            default:
                $status_desc = '待初审核中';
        }
        return $status_desc;
    }

    /**
     * 获取退单的详细信息
     * 订单详情
     * 退单详情
     * 退货商品信息
     * return json
     */
    public function getOrderDetail($id,$order_id)
    {
        $id = I('get.id') ? I('get.id') : $id;
        $order_id = I('get.order_id') ? I('get.order_id') : $order_id;
        if (!$id) {
            $return = array(
                'status' => false,
                'message' => '非法请求',
            );
            $this->ajaxReturn($return);
        }
        $refund_model = new RefundModel();
        $res = $refund_model->getOrderDetail($id,$order_id);
        $this->assign($res);
        if (!IS_AJAX) return;
        $html = $this->fetch('Admin@Refund:refundInfo');
        $return = array(
            'status' => true,
            'message' => '获取成功',
            'data' => $html
        );
        $this->ajaxReturn($return);
    }

    /**
     * 复审状态修改
     * 复审成功 / 失败
     */
    public function changeDeliveryFirst()
    {
        if (!IS_AJAX) {
            $this->error('错误的请求方式');
        }
        $id = I('post.id');
        $status = I('post.status'); //1-审核成功 2-失败
        $desc = I('post.desc');
        $current_price = I('post.price');
        $img = I('post.img');
        $bonus = I('post.bonus');
        $price = $current_price + $bonus; // 当前金额 + 奖金 = 总共退款金额
        $now = time();
        //`status` enum('5','4','3','2','0','6','1') NOT NULL DEFAULT '1' COMMENT '退款状态，1用户申请，2审核通过，3用户退货, 4确认退货, 5退货、退款完成,6重新申请',
        //`type` enum('2','1') NOT NULL DEFAULT '1' COMMENT '1退款，2退款退货',
        $info = M('b2c_refund_money')->where(['id' => $id])->find();
        if ((float)$info['price'] != (float)$price){
            $this->ajaxReturn(['status' => false, 'message' => '退款价格不相同', 'data' => '']);
        }
        if ($status) {
            //审核成功
            //先判断一些状态 pay_status ship_status
            //如果是退款 判断 sell_front 是否为1
            //如果是退货退款 判断 sell_ago 是否为1
            //`pay_status` enum('0','1') NOT NULL DEFAULT '0' COMMENT '付款状态：0-未付款、1-已支付',
            //`ship_status` enum('0','1') NOT NULL DEFAULT '0' COMMENT '发货状态：0-未发货、1-已发货',
            //`refund_status` enum('1','2','0') NOT NULL DEFAULT '0' COMMENT '退款状态：0-未申请，1-退款完成，2-退货退款完成',
            //`sell_ago` enum('1','0') NOT NULL DEFAULT '0' COMMENT '0未申请售后，1已售后',
            //`sell_front` enum('1','0') NOT NULL DEFAULT '0' COMMENT '0用户未申请售后之前退款状态，1用户申请售后之前退款状态',
            $order = M('b2c_orders')->where(['order_id' => $info['order_id']])->field('*')->find();
            $res = false;

            /**
             * `price_detail` decimal(20,2) NOT NULL DEFAULT '0.00' COMMENT '财务确认金额',
             * `finance_user` int(10) DEFAULT NULL COMMENT '财务操作员',
             * `finance_name` varchar(20) NOT NULL DEFAULT '' COMMENT '管理员名称',
             * `finance_confirm_t` int(10) unsigned DEFAULT NULL COMMENT '财务审核时间',
             * `finance_memo` longtext COMMENT '财务备注',
             * `finance_img` varchar(1000) NOT NULL DEFAULT '' COMMENT '财务上传的图片证明',
             */
            if ($order['pay_status'] == '1' && (($info['status'] == '4' && $info['type'] == '3' && $order['refund_ago_goods_status'] == '1') || ($info['status'] == '2' && $info['type'] == '2' && $order['refund_ago_money_status'] == '1') || ($info['status'] == '2' && $info['type'] == '1' && $order['refund_front_status'] == '1'))) {
                $res = true;
            }
            if ($res) {
                //操作时间流程
                $json_msg = [];
                if ($info['json_msg']) {
                    $json_msg = json_decode($info['json_msg'], true);
                    $json_msg['f'] = ['time' => $now];
                } else {
                    $json_msg['f'] = ['time' => $now];
                }

                $save = [
                    'status' => '5',
                    'price_detail' => $price,
                    'refund_bonus' => $bonus,
                    'finance_confirm_t' => $now,
                    'finance_memo' => $desc,
                    'finance_name' => session('manageInfo')['login_name'],
                    'finance_user' => session('manageInfo')['account_id'],
                    'finance_img' => $img,
                    'json_msg' => json_encode($json_msg)
                ];
                //

                $db = M();
                $db->startTrans();
                $save = M('b2c_refund_money')->where(['id' => $id])->save($save);

                //查询是部分退货还是全部退货 如果
                $msg = '退款成功';

                $mgnumArr = M('b2c_refund_money_goods')->where(['refund_money_id'=>$id,'order_id'=>$info['order_id']])->select();
                $refund_num = 0;
                foreach ($mgnumArr as $kk =>$value1){
                    $refund_num += $value1['num'];
                }
                 /***************冉 3-11修改 判断前后 退款，退货总数量是否等于购买数量************************/
                $sum_goods_num = '';
                // 查询售前退款完成
                if ($order['refund_front_status'] == '2') {

                    $sdb_b2c_refund_money_msg = M('b2c_refund_money')->where(['status'=>'5','type'=>'1','order_id'=>$info['order_id']])->find();
                    if ($sdb_b2c_refund_money_msg) {
                        $b2c_refund_money_goods = M('b2c_refund_money_goods')->where(['refund_money_id' => $sdb_b2c_refund_money_msg['id']])->select(); // 查询退款商品数组
                        foreach ($b2c_refund_money_goods as $v){
                            $sum_goods_num += $v['num'];
                        }
                    }
                }

                // 售后退款
                if ($order['refund_ago_money_status'] == '2') {
                    $sdb_b2c_refund_money_msg = M('b2c_refund_money')->where(['status'=>'5','type'=>'2','order_id'=>$info['order_id']])->find();
                    if ($sdb_b2c_refund_money_msg) {
                        $b2c_refund_money_goods = M('b2c_refund_money_goods')->where(['refund_money_id' => $sdb_b2c_refund_money_msg['id']])->select(); // 查询退款商品数组
                        foreach ($b2c_refund_money_goods as $v){
                            $sum_goods_num += $v['num'];
                        }
                    }
                }

                // 售后退款退货
                if ($order['refund_ago_goods_status'] == '2') {
                    $sdb_b2c_refund_money_msg = M('b2c_refund_money')->where(['status'=>'5','type'=>'3','order_id'=>$info['order_id']])->find();
                    if ($sdb_b2c_refund_money_msg) {
                        $b2c_refund_money_goods = M('b2c_refund_money_goods')->where(['refund_money_id' => $sdb_b2c_refund_money_msg['id']])->select(); // 查询退款商品数组
                        foreach ($b2c_refund_money_goods as $v){
                            $sum_goods_num += $v['num'];
                        }
                    }
                }

                $refund_num += $sum_goods_num;
                /************************************************************/

                if (intval($refund_num) == intval($order['itemnum'])) {
                    $s = ['refund_status' => $info['type'], 'status'=>'finish', 'order_msg'=> $msg];
                    $isPartRefund = false;
                } else {
                    $s = ['refund_status' => $info['type'], 'order_msg'=> '部分商品退款成功'];
                    $isPartRefund = true;
                }
                if ($info['type'] == '1') {
                    $s['refund_front_status'] = '2';
                } elseif($info['type'] == '2') {
                    $s['refund_ago_money_status'] = '2';
                } elseif($info['type'] == '3') {
                    $s['refund_ago_goods_status'] = '2';
                }

                $save2 = M('b2c_orders')->where(['order_id' => $info['order_id']])->save($s);

                //如果是退款还库存

                if ($info['type'] == '1') {
                    $save4 = $this->resetfreez($id, $info['local_id'],$info['order_id']);
                    if (!$save4['status']) {
                        $db->rollback();
                        $this->ajaxReturn($save4);
                    }
                }
                //sdb_b2c_bills 新增退款流水记录
                $add = [
                    'transaction_id'=>'',
                    'bill_id'=>'',
                    'local_id'=>$order['local_id'],
                    'member_id'=>$order['member_id'],
                    'payment_id'=>null,
                    'bill_type'=>'refunds',
                    'bills_source_id'=>2,
                    'money'=>$price,
                    'bonus_money'=>$bonus,
                    'time'=>$now,
//                    'createtime' =>$now,
                    'order_id'=>$info['order_id'],
                    'refund_id'=>$info['id'],
                    'store_work_logs' => $info['store_work_logs'],
                    'price_detail' => $price,
                    'finance_name' => session('manageInfo')['login_name'],
                    'finance_user' => session('manageInfo')['account_id'],
                    'finance_confirm_t' => $now,
                ];
                $save3 = M('b2c_bills')->add($add);

                //写日志 sdb_b2c_order_log
                $log = [
                    'rel_id' => $info['order_id'],
                    'op_id' => session('manageInfo')['account_id'],
                    'op_name' => session('manageInfo')['login_name'],
                    'alttime' => $now,
                    'bill_type' => 'order',
                    'behavior' => 'refunds',
                    'result' => 'SUCCESS',
                    'log_text' => $info['type'] == '1' ? '平台审核退款成功!' : '平台审核退货退款成功!',
                ];
                $save4 = M('b2c_order_log')->add($log);

                // 当前会员退款，1如果奖金有就退款到当前会员账号，2如果当前会员上级有分销提成就必须减去退款提成
                $refund_bonus = refund_bonus($order, $bonus, $price);

                if ($refund_bonus == false) {
                    $db->rollback();
                    $this->ajaxReturn(['status' => false, 'message' => '分销错误', 'data' => '']);
                }
				
				if ($bonus){ // 返回上级退款奖金
                    $distribution_member_up = M()->execute("update sdb_distribution_member set current_bonus = current_bonus + $bonus where member_id=$order[member_id]");
                    if ($distribution_member_up == false) {
                        $db->rollback();
                        $this->ajaxReturn(['status' => false, 'message' => '奖金退货失败', 'data' => '']);
                    }
                }

                //返回优惠卷
                $member = new OrderModel();
                if ($isPartRefund) {
                    // todo 优惠卷返回 部分退款
                    $items = M('b2c_refund_money_goods')
                        ->alias('a')
                        ->join(C('DB_PREFIX').'b2c_order_items b on a.item_id=b.item_id')
                        ->where(['a.refund_money_id'=>$id])
                        ->getField('store_pid', true);
                    foreach ($items as $item) {
                        $save5 = $member->isBackCoupon(2, $info['order_id'], $item, 1);
                        if ($save5['status'] === false) {
                            $db->rollback();
                            $return = ['status' => false, 'message' => '优惠卷返回失败', 'data' => ''];
                        }
                    }
                } else {
                    //全部退款
                    $save5 = $member->isBackCoupon(1, $info['order_id'], 0, 1);

                    if ($save5['status'] === false) {
                        $db->rollback();
                        $return = ['status' => false, 'message' => '优惠卷返回失败', 'data' => ''];
                    }
                }

                //var_dump($save ,$save2, $save3 , $save4 );exit;
                if ($save != false && $save2 != false && $save3 != false && $save4 != false && $refund_bonus != false) {
                    $db->commit();
                    $return = ['status' => true, 'message' => '操作成功,退款成功!', 'data' => ''];
                } else {
                    $db->rollback();
                    $return = ['status' => false, 'message' => '操作失败,系统错误', 'data' => ''];
                }
            } else {
                $return = ['status' => false, 'message' => '通过的前置条件没被满足,操作失败', 'data' => ''];
            }

        }

        $this->ajaxReturn($return);
    }

    /**
     * @param $id sdb_b2c_refund_money主键id
     */
    public function resetfreez($id, $local_id,$order_id) {

        $temp = M('b2c_refund_money_goods')
            ->alias('a')
            ->join(C('DB_PREFIX').'b2c_order_items b on a.item_id=b.item_id')
            ->field('a.num, b.product_id')
            ->where(['a.refund_money_id'=>$id,'a.order_id'=>$order_id])
            ->select();

        $db = new Model();
        $db->startTrans();
        if ($temp) {
            foreach ($temp as  $item) {

                /*更改*/
                $res = M('b2c_store_product')->where(['local_id'=>$local_id, 'product_id'=>$item['product_id']])->setDec('freez', $item['num']);

                if (!$res) {
                    $db->rollback();
                    return ['status'=>false, 'message'=>'退还库存出错', 'data'=>[]];
                }
            }

            $db->commit();
            return ['status'=>true, 'message'=>'执行成功', 'data'=>[]];
        } else {
            return ['status'=>false, 'message'=>'没有数据', 'data'=>[]];
        }
    }
}